<template>
  <div class="gantt-demo">
    <!-- <h1>甘特图拖拽演示</h1> -->

    <div class="controls">
      <button @click="saveData" :disabled="!hasChanges">保存数据</button>
      <button @click="resetData">重置数据</button>
      <button @click="exportData">导出JSON</button>
    </div>

    <div class="status" v-if="statusMessage">
      <div :class="['status-message', statusType]">{{ statusMessage }}</div>
    </div>

    <div class="gantt-container">
      <GanttChart
        ref="ganttChart"
        :apiUrl="apiUrl"
        :autoSave="false"
        :initialTasks="initialTasks"
        @task-updated="onTaskUpdated"
        @task-drag-end="onTaskDragEnd"
        @link-created="onLinkCreated"
        @save-success="onSaveSuccess"
        @save-error="onSaveError"
        @data-reset="onDataReset"
      />
    </div>

    <div class="data-display">
      <h3>当前数据 <small>(拖拽后自动更新)</small></h3>
      <pre>{{ JSON.stringify(currentData, null, 2) }}</pre>
    </div>
  </div>
</template>

<script>
import GanttChart from '@/components/GanttChart.vue';

export default {
  name: 'GanttDemo',
  components: {
    GanttChart,
  },
  data() {
    // 辅助函数：获取格式化的日期字符串，offset为天数偏移量
    const getFormattedDate = offset => {
      const date = new Date();
      date.setDate(date.getDate() + offset);
      return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式
    };

    // 获取当前日期
    const today = getFormattedDate(0);

    return {
      apiUrl: 'https://your-backend-api-url/tasks', // 替换为实际的API URL
      initialTasks: {
        data: [
          {
            id: 1,
            text: '项目计划A',
            start_date: today,
            duration: 20,
            progress: 0.4,
            open: true, // 默认展开子任务
          },
          {
            id: 2,
            text: '需求分析',
            start_date: today,
            duration: 4,
            parent: 1,
            progress: 1,
          },
          {
            id: 3,
            text: '设计阶段',
            start_date: getFormattedDate(4),
            duration: 5,
            parent: 1,
            progress: 0.8,
          },
          {
            id: 4,
            text: '开发阶段',
            start_date: getFormattedDate(9),
            duration: 8,
            parent: 1,
            progress: 0.2,
          },
          {
            id: 5,
            text: '测试阶段',
            start_date: getFormattedDate(17),
            duration: 3,
            parent: 1,
            progress: 0,
          },
          // 添加第二个根节点及其子任务
          {
            id: 6,
            text: '项目计划B',
            start_date: getFormattedDate(5),
            duration: 15,
            progress: 0.3,
            open: true, // 默认展开子任务
          },
          {
            id: 7,
            text: '市场调研',
            start_date: getFormattedDate(5),
            duration: 4,
            parent: 6,
            progress: 0.6,
          },
          {
            id: 8,
            text: '产品规划',
            start_date: getFormattedDate(9),
            duration: 3,
            parent: 6,
            progress: 0.5,
          },
          {
            id: 9,
            text: '发布计划',
            start_date: getFormattedDate(12),
            duration: 8,
            parent: 6,
            progress: 0,
          },
          // 添加第三个根节点及其子任务
          {
            id: 10,
            text: '项目计划C',
            start_date: getFormattedDate(10),
            duration: 18,
            progress: 0.1,
            open: true, // 默认展开子任务
          },
          {
            id: 11,
            text: '资源评估',
            start_date: getFormattedDate(10),
            duration: 3,
            parent: 10,
            progress: 0.8,
          },
          {
            id: 12,
            text: '技术选型',
            start_date: getFormattedDate(13),
            duration: 4,
            parent: 10,
            progress: 0.3,
          },
          {
            id: 13,
            text: '原型开发',
            start_date: getFormattedDate(17),
            duration: 11,
            parent: 10,
            progress: 0,
          },
        ],
        links: [
          { id: 1, source: 2, target: 3, type: 0 },
          { id: 2, source: 3, target: 4, type: 0 },
          { id: 3, source: 4, target: 5, type: 0 },
          // 第二个项目的任务链接
          { id: 4, source: 7, target: 8, type: 0 },
          { id: 5, source: 8, target: 9, type: 0 },
          // 第三个项目的任务链接
          { id: 6, source: 11, target: 12, type: 0 },
          { id: 7, source: 12, target: 13, type: 0 },
        ],
      },
      currentData: null,
      originalData: null,
      statusMessage: '',
      statusType: 'info', // 'info', 'success', 'error'
      hasChanges: false,
    };
  },
  mounted() {
    // 初始化后保存原始数据用于比较
    this.$nextTick(() => {
      this.currentData = this.$refs.ganttChart.getCurrentData();
      this.originalData = JSON.stringify(this.currentData);
    });
  },
  methods: {
    // 获取格式化的日期字符串，offset为天数偏移量
    getFormattedDate(offset) {
      const date = new Date();
      date.setDate(date.getDate() + offset);
      return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式
    },

    // 任务更新时的处理函数
    onTaskUpdated(data) {
      this.currentData = data;
      this.checkForChanges();
    },

    // 任务拖拽结束时的处理函数
    onTaskDragEnd(data) {
      this.currentData = data;
      this.showStatus('任务拖拽完成', 'success');
      this.checkForChanges();
    },

    // 链接创建时的处理函数
    onLinkCreated(data) {
      this.currentData = data;
      this.showStatus('任务链接已创建', 'success');
      this.checkForChanges();
    },

    // 保存成功的处理函数
    onSaveSuccess(response) {
      const message = response?.message || '数据已成功保存到后端';
      this.showStatus(message, 'success');
      this.originalData = JSON.stringify(this.currentData);
      this.checkForChanges();
    },

    // 保存错误的处理函数
    onSaveError(error) {
      this.showStatus(`保存失败: ${error.message}`, 'error');
    },

    // 数据重置的处理函数
    onDataReset(data) {
      this.currentData = data;
      this.originalData = JSON.stringify(data);
      this.showStatus('数据已重置', 'info');
      this.hasChanges = false;
    },

    // 手动保存数据
    saveData() {
      if (this.$refs.ganttChart) {
        this.$refs.ganttChart.save();
      }
    },

    // 重置数据
    resetData() {
      if (this.$refs.ganttChart) {
        this.$refs.ganttChart.reset();
      }
    },

    // 导出数据为JSON
    exportData() {
      if (this.$refs.ganttChart) {
        const jsonData = this.$refs.ganttChart.exportToJSON();

        // 创建下载链接
        const blob = new Blob([jsonData], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'gantt-data.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        this.showStatus('数据已导出为JSON文件', 'success');
      }
    },

    // 显示状态消息
    showStatus(message, type = 'info') {
      this.statusMessage = message;
      this.statusType = type;

      // 3秒后清除消息
      setTimeout(() => {
        if (this.statusMessage === message) {
          this.statusMessage = '';
        }
      }, 3000);
    },

    // 检查是否有未保存的更改
    checkForChanges() {
      this.hasChanges = JSON.stringify(this.currentData) !== this.originalData;
    },
  },
};
</script>

<style scoped>
.gantt-demo {
  padding: 20px;
}

.controls {
  margin-bottom: 20px;
}

button {
  margin-right: 10px;
  padding: 8px 16px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.status {
  margin-bottom: 20px;
}

.status-message {
  padding: 10px;
  border-radius: 4px;
}

.status-message.info {
  background-color: #e7f3fe;
  border-left: 6px solid #2196f3;
}

.status-message.success {
  background-color: #ddffdd;
  border-left: 6px solid #4caf50;
}

.status-message.error {
  background-color: #ffdddd;
  border-left: 6px solid #f44336;
}

.gantt-container {
  margin-bottom: 20px;
  border: 1px solid #ddd;
}

.data-display {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 300px;
  overflow-y: auto;
  background-color: #f9f9f9;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>
